<template>
  <div class="post-manager">
    <PostListBG />
    <!-- 发布新帖子卡片 -->
    <el-card class="post-card" shadow="never">
      <div class="post-header">
        <h3 class="card-title">发表新帖</h3>
        <el-divider />
      </div>
      <el-form :model="newPost" label-width="80px">
        <el-form-item label="标题">
          <el-input
            v-model="newPost.title"
            placeholder="请输入标题"
            clearable
            class="custom-input"
          />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="newPost.content"
            placeholder="请输入内容"
            type="textarea"
            :rows="4"
            clearable
            resize="none"
            class="custom-textarea"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="uploadPost" class="submit-btn">
            <i class="el-icon-upload2"></i> 发布帖子
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 帖子列表 -->
    <el-card class="post-card" shadow="never">
      <div class="post-header">
        <h3 class="card-title">最新帖子</h3>
        <el-divider />
      </div>
      <div
        v-for="post in posts"
        :key="post.post_id"
        class="post-item"
        @click="showPostDetail(post)"
      >
        <div class="post-content">
          <h4 class="post-title">{{ post.title }}</h4>
          <pre class="post-body">{{ post.content }}</pre>
          <div class="post-meta">
            <span class="meta-item">
              <i class="el-icon-user"></i>
              {{ post.username || "用户" + post.user_id }}
            </span>
            <span class="meta-item">
              <i class="el-icon-time"></i>
              {{ formatTime(post.created_at) }}
            </span>
            <div class="action-group">
              <el-button
                type="text"
                @click.stop="likePost(post)"
                class="like-btn"
              >
                <el-icon><Star /></el-icon>
                <i :class="['el-icon-thumb', post.isLiked ? 'liked' : '']"></i>
                {{ post.likes || 0 }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="showDetail"
      :title="currentPost.title"
      width="60%"
      class="post-dialog"
      @closed="handleDialogClose"
    >
      <div class="dialog-content">
        <div class="post-content">
          <p class="post-body">{{ currentPost.content }}</p>
          <div class="post-meta">
            <span class="meta-item">
              <i class="el-icon-user"></i>
              {{ currentPost.username || "用户" + currentPost.user_id }}
            </span>
            <span class="meta-item">
              <i class="el-icon-time"></i>
              {{ formatTime(currentPost.created_at) }}
            </span>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comment-section">
          <h4 class="comment-title">评论（{{ comments.length }}）</h4>
          <div v-if="comments.length === 0" class="empty-comments">
            <el-empty
              description="暂无评论，快来抢沙发吧~"
              :image-size="80"
            ></el-empty>
          </div>
          <div
            v-else
            v-for="comment in comments"
            :key="comment.comment_id"
            class="comment-item"
          >
            <div class="comment-header">
              <span class="comment-author">
                {{ comment.username || "用户" + comment.user_id }}
              </span>
              <span class="comment-time">
                {{ formatTime(comment.created_at) }}
              </span>
            </div>
            <p class="comment-content">{{ comment.content }}</p>
          </div>
        </div>

        <!-- 发表评论 -->
        <div class="new-comment">
          <el-input
            v-model="newComment.content"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            resize="none"
            class="comment-input"
          />
          <el-button type="primary" @click="uploadComment" class="submit-btn">
            <i class="el-icon-edit"></i> 发表评论
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { useRouter } from 'vue-router';
import PostListBG from '../../components/PostListBG.vue'

const router = useRouter();

export default {
  components: {
    PostListBG // 注册组件
  },
  data() {
    return {
      posts: [],
      comments: [],
      newPost: { title: "", content: "" },
      newComment: { content: "" },
      currentPost: {},
      showDetail: false,
    };
  },
  methods: {
    async fetchPosts() {
      try {
        const res = await this.$axios.get("/posts");
        this.posts = res.data.map((post) => ({
          ...post,
          isLiked: false,
        }));
      } catch (error) {
        this.$message.error("获取帖子失败");
      }
    },

    async showPostDetail(post) {
      try {
        this.currentPost = post;
        this.showDetail = true; // 确保设置为true

        const res = await this.$axios.get(`/comments/${post.post_id}`);
        this.comments = res.data;
        console.log("获取到的评论数据:", this.comments); // 调试日志
      } catch (error) {
        console.error("获取评论失败:", error); // 详细错误日志
        this.$message.error("获取评论失败");
        this.comments = [];
      }
    },

    async likePost(post) {
      try {
        if (this.$store.state.user_id === null) {
          // 如果状态没有加载，跳转到登录页面
          router.push("/user/login"); // 跳转到登录页面
          return; // 防止继续执行后续代码
        }
        const userId = this.$store.state.user_id;
        const formData = new FormData();
        formData.append("user_id", userId);

        // 发送点赞请求
        const response = await this.$axios.post(
          `/posts/${post.post_id}/like`,
          formData
        );

        // 如果后端返回成功
        if (response.status === 200) {
          post.isLiked = true;
          post.likes += 1;
          this.$message.success(" 点赞成功");
        }
      } catch (error) {
        // 处理错误
        if (error.response && error.response.status === 400) {
          const errorMessage = error.response.data.error;
          if (errorMessage.includes("user has already liked it")) {
            this.$message.error(" 您已点赞过");
          } else {
            this.$message.error(" 操作失败：帖子不存在或服务器异常");
          }
        } else {
          this.$message.error(" 操作失败");
        }
      }
    },

    async uploadPost() {
      if (this.$store.state.user_id === null) {
        // 如果状态没有加载，跳转到登录页面
        router.push("/user/login"); // 跳转到登录页面
        this.$message.error("登录状态失效，请重新登录！");
        return; // 防止继续执行后续代码
      }
      const userId = this.$store.state.user_id;
      const formData = new FormData();

      formData.append("user_id", userId);
      formData.append("title", this.newPost.title);
      formData.append("content", this.newPost.content);

      this.$axios
        .post("/posts/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(() => {
          this.$message.success("发布成功！");
          this.newPost.title = "";
          this.newPost.content = "";
          this.fetchPosts();
        })
        .catch((error) => {
          console.error("帖子上传失败：", error);
          this.$message.error("发布失败，请重试！");
        });
    },

    async uploadComment() {
      if (!this.newComment.content.trim()) return; // 检查是否为空或仅包含空白字符

      try {
        if (this.$store.state.user_id === null) {
          // 如果状态没有加载，跳转到登录页面
          this.$router.push("/user/login"); // 跳转到登录页面
          this.$message.error("登录状态失效，请重新登录！");
          return; // 防止继续执行后续代码
        }
        const userId = this.$store.state.user_id;
        const formData = new FormData();

        formData.append("user_id", userId);
        formData.append("content", this.newComment.content);

        this.$axios
          .post(`/comments/${this.currentPost.post_id}/upload`, formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then(() => {
            this.$message.success("评论发表成功！");
            this.newComment.content = "";
            this.showPostDetail(this.currentPost);
          })
          .catch((error) => {
            console.error("评论上传失败：", error);
            this.$message.error("评论发表失败，请重试！");
          });
      } catch (error) {
        console.error("评论上传失败：", error);
        this.$message.error("评论发表失败，请重试！");
      }
    },

    handleDialogClose() {
      this.newComment.content = "";
    },

    formatTime(dateString) {
      return new Date(dateString).toLocaleString();
    },
  },
  mounted() {
    this.fetchPosts();
  },
};
</script>

<style scoped>
.post-manager {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.post-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: 1px solid #ebeef5;
}

.card-title {
  color: #303133;
  font-size: 20px;
  margin: 0;
}

.post-item {
  padding: 16px;
  margin: 12px 0;
  background: #fafafa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.post-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.post-title {
  color: #303133;
  margin: 0 0 8px;
  font-size: 16px;
}

.post-body {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 12px;
  white-space: pre-wrap; /* 保留换行符并允许自动换行 */
  word-wrap: break-word; /* 强制长文本换行 */
  overflow-wrap: break-word; /* 兼容性处理 */
  max-width: 100%; /* 确保内容不超过容器宽度 */
  overflow: auto; /* 如果内容过长，显示滚动条 */
}

.post-meta {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.meta-item {
  margin-right: 16px;
  display: flex;
  align-items: center;
}

.meta-item i {
  margin-right: 4px;
}

.action-group {
  margin-left: auto;
}

.like-btn {
  background-color: #7abbfc; /* 蓝色 */
  color: white;
  border-radius: 20px; /* 圆角 */
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.like-btn:hover {
  background-color: #5be3a6;
  transform: scale(1.25);
}

.like-btn i {
  margin-right: 8px;
  font-size: 16px;
}

.like-btn span {
  font-size: 10px;
  font-weight: bold;
}

.liked {
  color: #067df4;
}

.post-dialog {
  display: block !important;
  z-index: 2000 !important;
}

.dialog-content {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.comment-section {
  margin-top: 24px;
}

.comment-title {
  color: #303133;
  font-size: 16px;
  margin-bottom: 16px;
}

.empty-comments {
  padding: 40px 0;
  text-align: center;
  background: #fff;
  border-radius: 8px;
}

.comment-item {
  padding: 12px;
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  color: #303133;
  font-weight: 500;
  margin-right: 12px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  color: #606266;
  margin: 0;
  line-height: 1.5;
}

.new-comment {
  margin-top: 24px;
}

.comment-input {
  margin-bottom: 12px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 14px;
}

.custom-input :deep(.el-input__inner) {
  border-radius: 8px;
}

.custom-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  padding: 12px;
}
</style>